package demo3;

import java.util.*;

public class Print {
    public ArrayList<ArrayList<Integer>> Print (TreeNode pRoot) {
        ArrayList<ArrayList<Integer>> list = new ArrayList<>();
        if(pRoot == null) {
            return list;
        }
        Queue<TreeNode> queue = new LinkedList<>();
        queue.offer(pRoot);
        int index = 0;
        int curLen = 1;// 当前剩余长度
        int nextLen = 0;// 下一个长度
        while(!queue.isEmpty()) {
            list.add(new ArrayList<>());
            while(curLen-- != 0) {
                TreeNode poll = queue.poll();
                list.get(index).add(poll.val);
                if(poll.left != null) {
                    queue.offer(poll.left);
                    nextLen++;
                }
                if(poll.right != null) {
                    queue.offer(poll.right);
                    nextLen++;
                }
            }
            curLen = nextLen;
            nextLen = 0;
            index++;
        }
        for (int i = 1; i < list.size(); i += 2) {
            Collections.reverse(list.get(i));
        }
        return list;
    }
}
